// Copyright 2007 Google Inc. All Rights Reserved.

package com.google.jessewilson.codesearch.commandlinesearch;

import ca.odell.glazedlists.FunctionList;
import com.google.inject.Inject;
import com.google.jessewilson.codesearch.api.Query;
import com.google.jessewilson.codesearch.api.SearchProvider;
import com.google.jessewilson.codesearch.api.spi.SearchProviderParameters;
import com.google.jessewilson.codesearch.api.spi.SearchProviderParametersEditor;
import com.google.jessewilson.codesearch.ide.QueryHistory;
import com.google.jessewilson.codesearch.ui.HistoryField;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;

import javax.swing.*;

/**
 * @author jessewilson
 */
class ClsSearchProviderParametersEditor
    implements SearchProviderParametersEditor {

  private final HistoryField<Query> extraArguments;

  private JPanel panel;

  @Inject
  public ClsSearchProviderParametersEditor(QueryHistory queryHistory) {
    this.extraArguments = new HistoryField<Query>(new FunctionList.Function<Query,String>() {
      public String evaluate(Query query) {
        ClsSearchProviderParameters queryExtra = (ClsSearchProviderParameters) query.getSearchProviderParameters();
        return queryExtra != null ? queryExtra.getExtraArguments() : null;
      }
    });

    // tmao(2007-09-11): Commenting this out pending discussion on how we're
    // going to handle externalizing state.
//    extraArguments.setHistory(queryHistory.getSnapshot());

    FormLayout formLayout = new FormLayout(
        "right:min, 3px, left:pref:grow",
        "min");
    panel = new JPanel(formLayout);

    CellConstraints cc = new CellConstraints();
    panel.add(new JLabel("Extra Arguments:"), cc.xy(1, 1));
    panel.add(extraArguments.getComponent(), cc.xy(3, 1, "fill, fill"));
  }

  public JPanel getComponent() {
    return panel;
  }

  public void setValue(SearchProviderParameters parameters) {
    assert(parameters != null);
    ClsSearchProviderParameters clsParameters =
        (ClsSearchProviderParameters) parameters;
    this.extraArguments.setValue(clsParameters.getExtraArguments());
  }

  public SearchProviderParameters getValue() {
    return new ClsSearchProviderParameters(extraArguments.getValue(), true);
  }

  public void setAction(Action action) {
    extraArguments.setAction(action);
  }

  public SearchProvider getSearchProvider() {
    return new ClsSearchProvider();
  }

  public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() { public void run() {
          JPanel panel = new ClsSearchProviderParametersEditor(null).panel;
          panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

          JFrame frame = new JFrame();
          frame.getContentPane().add(panel);
          frame.setSize(400, 200);
          frame.setLocationRelativeTo(null);
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setVisible(true);
      }});
  }
}
